<template>
  <el-dialog :title="title" :visible.sync="isShow" @close="btnCancel">
    <el-form
      ref="roleForm"
      :model="roleForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="isShow = false">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { addRoles, editRoles, getRoleInfoData } from '@/api/settings'
export default {
  name: 'AddRole',
  data() {
    return {
      isShow: false,
      //   表单数据对象
      roleForm: {},
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 12, message: '名字长度在2到12以内', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.roleForm.id ? '修改角色' : '添加角色'
    }
  },
  methods: {
    // 发送请求
    async btnOK() {
      // 1、表单校验
      await this.$refs.roleForm.validate()
      // 2、发送请求，处理数据
      if (this.roleForm.id) {
        // 修改
        await editRoles(this.roleForm)
        this.$message.success('修改成功')
      } else {
        // 添加
        await addRoles(this.roleForm)
        this.$message.success('添加成功')
      }
      // 3、提示成功/失败  关闭弹框·
      this.isShow = false
      this.$emit('update')
    },
    // 获取回显数据
    async getInfoData(id) {
      const { data } = await getRoleInfoData(id)
      this.roleForm = data
      this.isShow = true
    },
    // 重置事件
    btnCancel() {
      this.roleForm = {}
    }
  }
}
</script>

<style>
</style>
